<template>
  <el-dialog v-model="dialogVisible" title="设备信息确认" width="700px" :close-on-click-modal="false" @close="handleDialogClose">
    <!-- 基本信息展示 -->
    <el-card class="mb-4">
      <template #header>
        <div class="card-header">
          <span>设备基本信息</span>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="MAC地址">{{ currentRow?.mac || '-' }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ currentRow?.ip || '-' }}</el-descriptions-item>
        <el-descriptions-item label="位置">{{ currentRow?.location || '-' }}</el-descriptions-item>
        <el-descriptions-item label="告警时间">{{ currentRow?.warnTime || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 表单内容 -->
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" label-position="right">
      <!-- 设备类型 -->
      <el-form-item label="设备类型" prop="type">
        <el-cascader style="width: 325px;" v-model="formData.type" :options="searchData" placeholder="请选择设备类型"
                     @change="onDeviceChange" clearable />
      </el-form-item>

      <!-- 设备归属 -->
      <el-form-item label="设备归属" prop="belong">
        <el-radio-group v-model="formData.belong">
          <el-radio v-for="option in belongOptions" :key="option.value" :label="option.value" :border="true">
            {{ option.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 补充信息 -->
      <el-form-item label="补充信息" prop="remark">
        <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请补充说明（如：设备位置、异常情况等）" />
      </el-form-item>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleButtonClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, reactive, computed, watch, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import {suspectOption, deviceTypeOption} from '@/api/suspect'

const searchData = ref(null)
const loading = ref(false)
const isClosing = ref(false)

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  currentRow: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:visible', 'submit', 'cancel'])

// 控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// 表单ref
const formRef = ref(null)
const submitting = ref(false)

// 归属选项
const belongOptions = [
  {value: '1', label: '是，确认是本场所的设备'},
  // {value: '2', label: '否，非本酒店设备'},
  // {value: '0', label: '不确定'}
]

// 表单数据
const formData = reactive({
  belong: '',
  remark: '',
  type: []
})

// 表单验证规则
const rules = {
  type: [
    {required: true, message: '请选择设备类型', trigger: 'change'}
  ],
  belong: [
    {required: true, message: '请选择设备归属', trigger: 'change'}
  ],
  remark: [
    {required: false, message: '请输入补充信息', trigger: 'blur'}
  ]
}

// 统一的关闭处理函数
const handleClose = () => {
  if (isClosing.value) return
  isClosing.value = true

  formRef.value?.resetFields()
  emit('cancel')

  // 重置状态
  setTimeout(() => {
    isClosing.value = false
  }, 100)
}

// 处理对话框关闭（点击 x 按钮）
const handleDialogClose = () => {
  handleClose()
}

// 处理取消按钮点击
const handleButtonClose = () => {
  handleClose()
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    submitting.value = true

    // 组装提交数据
    const submitData = {
      ...formData,
      mac: props.currentRow?.mac,
      ip: props.currentRow?.ip,
      location: props.currentRow?.location,
      foundTime: props.currentRow?.foundTime
    }

    // 特殊处理：当选择"非本酒店设备"或"不确定"时，检查是否填写补充说明
    if ((formData.belong === 'no' || formData.belong === 'unknown') && !formData.remark) {
      ElMessage.warning('请填写补充说明以说明具体情况')
      return
    }
    emit('submit', submitData)
    handleClose()
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('请完善表单信息')
  } finally {
    submitting.value = false
  }
}

// 监听设备归属变化，处理补充信息必填逻辑
watch(() => formData.belong, (newVal) => {
  if (newVal === 'no' || newVal === 'unknown') {
    rules.remark[0].required = true
  } else {
    rules.remark[0].required = false
  }
})

// 监听currentRow变化,反显数据
watch(() => props.currentRow, (newVal) => {
  if (newVal) {
    formData.type = newVal.type || []
    formData.belong = newVal.belong || ''
    formData.remark = newVal.remark || ''
    props.currentRow.location = newVal.address || ''
  }
}, {immediate: true})

// 生命周期
onMounted(() => {
  loadData()
})

// 处理新接口返回的设备类型数据
const processDeviceTypeData = (data) => {
  return data.map(item => ({
    value: item.value,
    label: item.label
  }))
}

// 获取数据
const loadData = async () => {
  try {
    loading.value = true
    // 使用新的API接口获取设备类型数据
    const res = await deviceTypeOption()
    if (res?.data) {
      searchData.value = processDeviceTypeData(res.data)
    }
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

const onDeviceChange = (deviceType) => {
  // 由于新接口返回的数据结构变化，这里直接使用选中的值
  formData.type = deviceType
}
</script>

<style scoped>
.el-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mb-4 {
  margin-bottom: 16px;
}

.mr-2 {
  margin-right: 8px;
}

:deep(.el-select-dropdown__item) {
  padding: 8px 12px;
}

:deep(.el-icon) {
  font-size: 16px;
}
</style>